package com.gr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.entity.*;
import com.gr.service.IAdminRoleService;
import com.gr.service.IAdminService;
import com.gr.service.IResourceService;
import com.gr.service.IRoleResourceService;
import com.gr.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guoran
 * @since 2022-05-07
 */
@RestController
@RequestMapping("/user")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IResourceService resourceService;
    @Autowired
    private IRoleResourceService roleResourceService;
    @Autowired
    private IAdminRoleService adminRoleService;
    /*@GetMapping("/login")
    public ResultEntity<Admin> login(String username,String password){
        //mybatisplus查询单个方法
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username).eq("password",password);
        Admin one = adminService.getOne(wrapper);
        if (one==null){
            return ResultEntity.error("账号密码错误");
        }else {
            return ResultEntity.ok(one);
        }
    }*/
    @GetMapping("/login")
    public Map<String,String> login(String username, String password){
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();//封装查询条件
        //第一个参数是字段名，第二个参数是字段对应的值
        wrapper.eq("username",username).eq("password",password);//like模糊查、between、gt大于ge大于等于，le小于等于
        //List<User> users = ud.selectList(wrapper);//参数封装查询条件
        Admin admin = adminService.getOne(wrapper);//list查完封装到list集合，one查询一条
        Map<String,String> map=new HashMap<>();//定义返回的map
        if (admin==null){
            map.put("msg","登录失败");
        }else {
            map.put("msg","登录成功");
            Map<String,String> jwtMap=new HashMap<>();//定义参数map
            jwtMap.put("id",admin.getId()+"");
            jwtMap.put("username",username);
            jwtMap.put("status",admin.getStatus()+"");
            String token = JwtUtils.getToken(jwtMap);
            map.put("token",token);
        }
        return map;
    }

    @GetMapping("/showAll")
    public ResultEntity<List<Admin>> showAll(){
        List<Admin> list = adminService.list();
        return ResultEntity.ok(list);
    }

    @PostMapping("/insert")
    public ResultEntity<Admin> insert(@RequestBody Admin admin){
        adminService.save(admin);
        return ResultEntity.ok();
    }

    @GetMapping("/selectById/{userId}")
    public ResultEntity<Admin> selectById(@PathVariable("userId") Integer userId){
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("id",userId);
        Admin one = adminService.getOne(wrapper);
        return ResultEntity.ok(one);
    }

    @PutMapping("/update")
    public ResultEntity<Admin> update(@RequestBody Admin admin){
        adminService.updateById(admin);
        return ResultEntity.ok();
    }

    @GetMapping("/selectRoleId/{userId}")
    public ResultEntity<AdminRole> selectRoleId(@PathVariable("userId") Integer userId){
        QueryWrapper<AdminRole> wrapper=new QueryWrapper();
        wrapper.eq("admin_id",userId);
        AdminRole one = adminRoleService.getOne(wrapper);
        return ResultEntity.ok(one);
    }

    @GetMapping("/selectResourcesByUserId")
    public ResultEntity<List<Resource>> selectResourcesByUserId(){
        //toDo 1.先根据登录人id查询出对应角色id
        //1.查询出当前登陆人的权限列表
        int adminId=1;
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("admin_id",adminId);
        List<AdminRole> list = adminRoleService.list(wrapper);
        //1.1查询出当前登陆人的角色id1,2，3
        List<Integer> roleIdList = list.stream().map((adminRole) -> {
            return adminRole.getRoleId();
        }).collect(Collectors.toList());

        QueryWrapper wrapper1=new QueryWrapper();
        //toDo 此处报500
        wrapper1.in("role_id",roleIdList);//mybatis对应的枚举方法,没给字段
        //1.2到role_resource表里面根据1,2,3查询出当前登陆人的权限id。
        List<RoleResource> recList = roleResourceService.list(wrapper1);
        System.out.println(recList);
        List<Integer> recIdList = recList.stream().map((roleResource) -> {
            return roleResource.getResourceId();
        }).collect(Collectors.toList());
        //1.3到resource表里面查询出当前登陆人的权限列表
        List<Resource> resources = (List<Resource>) resourceService.listByIds(recIdList);
        //2.过滤出一级权限
        List<Resource> firstLevelResource = resources.stream().filter((resource) -> {
            return resource.getParentId()==0;
        }).peek((resource)->{
            //根据父菜单的id，找到该父菜单对应的子菜单，单独定义出来一个方法
            List<Resource> children = getChildrenByPid(resource.getMenuId(), resources);
            resource.setResourceList(children);//3.给一级权限以递归的方式设置孩子。
        }).collect(Collectors.toList());
        return ResultEntity.ok(firstLevelResource);
    }
    //根据父菜单的id，来找父菜单下面的子菜单
    private List<Resource> getChildrenByPid(long pid,List<Resource> resources){//寻找子节点
        return resources.stream().filter((resource) -> {
            return resource.getParentId().equals(pid);//小坑
        }).peek((resource)->{//给属性赋值
            //想办法找到resource对象的孩子就好了,list集合放入参数
            List<Resource> list = getChildrenByPid(resource.getMenuId(), resources);//递归，会依次找孩子，循环到没有孩子
            resource.setResourceList(list);//给二级菜单对应的三级菜单赋值
        } ).collect(Collectors.toList());
    }
}